package com.billing.web.controller.approve;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.billing.config.ServiceConfig;
import com.billing.model.entity.TAttachmentStorage;
import com.billing.model.entity.TAttendance;
import com.billing.model.entity.TBorrow;
import com.billing.model.entity.TClocktime;
import com.billing.model.entity.TCurrency;
import com.billing.model.entity.TFillcard;
import com.billing.model.entity.TLeave;
import com.billing.model.entity.TMaindata;
import com.billing.model.entity.TOrganization;
import com.billing.model.entity.TOvertime;
import com.billing.model.entity.TRecord;
import com.billing.model.entity.TSchedulingdetails;
import com.billing.model.entity.TUser;
import com.billing.model.entity.TUserPay;
import com.billing.service.AttachmentStorageService;
import com.billing.service.AttendanceService;
import com.billing.service.BorrowService;
import com.billing.service.ClocktimeService;
import com.billing.service.CurrencyService;
import com.billing.service.FillcardService;
import com.billing.service.LeaveService;
import com.billing.service.MaindataService;
import com.billing.service.ManagerPermissionsService;
import com.billing.service.OvertimeService;
import com.billing.service.RecordService;
import com.billing.service.SchedulingdetailsService;
import com.billing.service.UserBeanService;
import com.billing.service.UserPayService;
import com.billing.service.UserService;
import com.billing.utils.DateUtil;
import com.billing.web.controller.attendance.AttendanceController;

/**
 * 审批信息
 *
 */
@RequestMapping(value="/approve")
@Controller
public class ExamineController {
	@Resource
	private RecordService recordService;
	@Resource
	private MaindataService maindataService;
	@Resource
	private LeaveService leaveService;
	@Resource
	private OvertimeService overtimeService;
	@Resource
	private UserBeanService userBeanService;
	@Resource
	private UserService userService;
	@Resource
	private UserPayService userPayService;
	@Resource
	private BorrowService borrowService;
	@Resource
	private FillcardService fillcardService;
	@Resource
	private AttendanceService attendanceService;
	@Resource
	private SchedulingdetailsService schedulingdetailsService;
	@Resource
	private ClocktimeService clocktimeService;
	@Resource
	private AttachmentStorageService attachmentStorageService;
	@Resource
	private CurrencyService currencyService;
	@Resource
	private ManagerPermissionsService managerService;
	
	SimpleDateFormat mdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@Resource
	AttendanceController attendanceController=new AttendanceController();
	
	/**
	 * 后台审批办理
	 * @param request
	 * @param model
	 */
	@RequestMapping(value="/gotoApprove",method=RequestMethod.POST)
	@ResponseBody
	public String gotoApprove(HttpServletRequest request, Model model){
		String msg=null;
		long handletime=new Date().getTime();
		String docid=request.getParameter("docid");
		String remarktype=request.getParameter("remarktype");
		String remark=request.getParameter("remark");
		Object mid=request.getSession().getAttribute("managerid");
		Object uname=request.getSession().getAttribute("username");
		String managerid=String.valueOf(mid);
		String username=String.valueOf(uname);
		TMaindata maindata=maindataService.selectTMaindataById(docid);
		//获取当前审批的记录
		TRecord record=recordService.getTRecordByDocunid(docid, "1");
		//审批
		if(record.getNodestatus()==1){
			//不是最后一个节点
			//更新当前记录数据的状态以及启动下个节点。
			int nodesort = record.getNodesort()+1;
			//通过节点路径查询 实例id  与    记录数据  
			TRecord nextRecord = recordService.getTRecordByDidAndSort(docid, String.valueOf(nodesort));
			//update  record
			
			record.setEndtime(handletime);
			record.setMidifytime(handletime);
			//实际审批人
			record.setFactuserid(Integer.parseInt(managerid));
			record.setFactusername(username);
			record.setDocstatus(3);
			record.setHandlestatus(1);
			if(remarktype!=null && remarktype!="" && !"".equals(remarktype)){
				record.setRemarktype(Integer.parseInt(remarktype));
			}
			if(remark!=null && remark!="" && !"".equals(remark)){
				record.setRemark(remark);
			}
			int falre=recordService.updateTRecord(record);
			if(falre>0){
				
				//判断是否同意审批 ，如果是不同意就结束流程。
				if(record.getRemarktype()==1){
					//同意//update  nextRecord
					nextRecord.setDocstatus(1);
					nextRecord.setStarttime(handletime);
					int falren=recordService.updateTRecord(nextRecord);
					if(falren>0){
//						msg="{\"code\":\"1\",\"msg\":\"审批办理成功\"}";
						msg="ok";
					}else{
//						msg="{\"code\":\"2\",\"msg\":\"审批办理失败\"}";
						msg="no";
					}
					maindata.setAuthorid(record.getNextuserid());
					maindata.setAuthorname(record.getNextusername());
					String allreaders=maindata.getAllreaders()+","+nextRecord.getUserid();
					maindata.setAllreaders(allreaders);
				}else if(record.getRemarktype()==2){
					//不同意
					maindata.setStatus(2);
					maindata.setPassstatus(2);
				}
				//update maindata
				maindata.setMidifytime(handletime);
				String enduser=maindata.getEnduser();
				if(enduser!=null){
					enduser=enduser+","+record.getUserid();
				}else{
					enduser=record.getUserid()+"";
				}
				maindata.setEnduser(enduser);
				int falm=maindataService.updateTMaindata(maindata);
				if(falm>0){
//					msg="{\"code\":\"1\",\"msg\":\"审批办理成功\"}";
					msg="ok";
				}else{
//					msg="{\"code\":\"2\",\"msg\":\"审批办理失败\"}";
					msg="no";
				}
			}else{
//				msg="{\"code\":\"2\",\"msg\":\"审批办理失败\"}";
				msg="no";
			}
			
		}else if(record.getNodestatus()==2){
			//最后节点
			//update  record
			record.setDocstatus(3);
			record.setHandlestatus(1);
			record.setEndtime(handletime);
			record.setMidifytime(handletime);
			//实际审批人
			record.setFactuserid(Integer.parseInt(managerid));
			record.setFactusername(username);
			if(remarktype!=null && remarktype!="" && !"".equals(remarktype)){
				record.setRemarktype(Integer.parseInt(remarktype));
			}
			if(remark!=null && remark!=null && !"".equals(remarktype)){
				record.setRemark(remark);
			}
			int falre=recordService.updateTRecord(record);
			if(falre>0){
				//已归档
				//update maindata
				maindata.setMidifytime(handletime);
				maindata.setEndtime(handletime);
				maindata.setStatus(2);
				if(record.getRemarktype()==1){
					maindata.setPassstatus(1);
				}else if(record.getRemarktype()==2){
					maindata.setPassstatus(2);
				}
				int falm=maindataService.updateTMaindata(maindata);
				if(falm>0){
					//归档操作
					//判断是否存在抄送，如无：直接归档，否则等待抄送已读后归档
					int num=recordService.getRecordCopyNum(docid);
					if(num>0){
						//存在抄送，不归档   启动抄送状态
						int falc=recordService.updateTRecordCopyStatus(docid,String.valueOf(handletime));
						if(falc>0){
//							msg="{\"code\":\"1\",\"msg\":\"审批办理成功,存在抄送,未归档\"}";
							msg="ok";
						}
					}else{
						//不存在抄送，归档
//						msg="{\"code\":\"1\",\"msg\":\"审批办理成功,已归档\"}";
						msg="ok";
					}
					//验证业务类型
					TUser userbiss=new TUser();
					if(maindata.getType()==1){//请假
						TLeave leave=leaveService.getTLeaveById(maindata.getBusinessid());
						if(leave!=null){
							userbiss=userService.selectTUserId(String.valueOf(leave.getUserid()));
							List<TClocktime> clolist=clocktimeService.getTClocktimeByTime(leave.getStarttime(), leave.getEndtime(), userbiss.getSchedulingId());
							List<TAttendance> newattlist=new ArrayList<TAttendance>();
							List<TAttendance> updateattlist=new ArrayList<TAttendance>();
							if(clolist!=null){
								setLesveAttendance(clolist, newattlist, updateattlist, userbiss);
							}else{
								msg="{\"code\":\"2\",\"msg\":\"获取排班信息失败\"}";
							}
							if(newattlist!=null&&newattlist.size()>0){
								for (TAttendance newatt : newattlist) {
									attendanceService.insertTAttendance(newatt);
								}
							}
							if(updateattlist!=null&&updateattlist.size()>0){
								for (TAttendance updateatt : updateattlist) {
									attendanceService.updateTAttendance(updateatt);
								}
							}
						}
					}
					if(maindata.getType()==5){//补卡申请修改
						TFillcard fill=fillcardService.getTFillcardById(maindata.getBusinessid());
						if(fill!=null){
							TAttendance att=attendanceService.selectTAttendanceId(String.valueOf(fill.getAttendanceid()));
							if(att!=null){
								if(fill.getType()==1){
									att.setStarttime1(fill.getFilltime());
									att.setResults1(0);
								}else if(fill.getType()==2){
									att.setEndtime1(fill.getFilltime());
									att.setResults2(0);
								}else if(fill.getType()==3){
									att.setStarttime2(fill.getFilltime());
									att.setResults3(0);
								}else if(fill.getType()==4){
									att.setEndtime2(fill.getFilltime());
									att.setResults4(0);
								}else if(fill.getType()==5){
									att.setStarttime3(fill.getFilltime());
									att.setResults5(0);
								}else if(fill.getType()==6){
									att.setEndtime3(fill.getFilltime());
									att.setResults6(0);
								}
								attendanceService.updateTAttendance(att);
							}else{
								Long date=fill.getFilltime();//重置服务器当前时间
								TSchedulingdetails details=schedulingdetailsService.getTSchedulingdetailsById(fill.getDetailsid());
								if(date-fill.getFilltime()<=60000&&date-fill.getFilltime()>=-60000){
									date=fill.getFilltime();
								}
								TClocktime cktim=new TClocktime();
								String type=String.valueOf(fill.getType());
								userbiss=userService.selectTUserId(String.valueOf(fill.getUserid()));
								attendanceController.insertTAttendance(userbiss, details, cktim, type, date,"0", "0", 0, 0, 
										null, 0, maindata.getOrganizationId(),2);
							}
						}
					}
				}else{
//					msg="{\"code\":\"2\",\"msg\":\"审批办理失败\"}";
					msg="no";
				}
			}else{
//				msg="{\"code\":\"2\",\"msg\":\"审批办理失败\"}";
				msg="no";
			}
			
			//
		}
		Map<String, Object> map = new HashMap<>();
		map.put("date", msg);
		JSONObject jsonobj = JSONObject.fromObject(map);
		return jsonobj.toString();
	}
	
	/**
	 * 后台查询审批内容
	 * @param request
	 * @param model
	 */
	@RequestMapping(value="/lookapprovemain",method=RequestMethod.GET)
	public String lookapprovemain(HttpServletRequest request, Model model){
		String msg=null;
		String id=request.getParameter("id");
		String type=request.getParameter("type");
		TMaindata maindata=maindataService.getMaindataById(id);
		List<TRecord> list=recordService.getRecordListByApp(id);
		request.setAttribute("list", list);
		request.setAttribute("maindata", maindata);
		Date Timestamp=new Date();
		request.setAttribute("Timestamp", Timestamp);
		if("1".equals(type)){//1:请假，2：加班，3：通用，4：借钱，5：补卡
			msg="approve/lookleave";
		}else if("2".equals(type)){
			msg="approve/lookovertime";
		}else if("3".equals(type)){
			msg="approve/lookgoods";
		}else if("4".equals(type)){
			msg="approve/lookborrow";
		}else if("5".equals(type)){
			msg="approve/fillcard";
		}
		return msg;
	}
	/**
	 * 后台审批办理内容
	 * @param request
	 * @param model
	 */
	@RequestMapping(value="/approvemain",method=RequestMethod.GET)
	public String approvemain(HttpServletRequest request, Model model){
		String msg=null;
		String id=request.getParameter("id");
		String type=request.getParameter("type");
		TMaindata maindata=maindataService.getMaindataById(id);
		List<TRecord> list=recordService.getRecordListByApp(id);
		request.setAttribute("list", list);
		request.setAttribute("maindata", maindata);
		Date Timestamp=new Date();
		Date Endtimestamp= new Date();
		request.setAttribute("Timestamp", Timestamp);
		request.setAttribute("Endtimestamp", Endtimestamp);
		//1:请假，2：加班，3：通用，4：借钱，5：补卡
		if("1".equals(type)){
			msg="approve/leaveApprove";
		}else if("2".equals(type)){
			msg="approve/overtimeApprove";
		}else if("3".equals(type)){
			msg="approve/encyApprove";
		}else if("4".equals(type)){
			msg="approve/borrowApprove";
		}else if("5".equals(type)){
			msg="approve/fillcardApprove";
		}
		return msg;
	}
	/**
	 * 后台审批管理页面
	 * @param request
	 * @param model
	 */
	@RequestMapping(value="/index",method=RequestMethod.GET)
	public String index(HttpServletRequest request, Model model){
		//return null;
		Integer userid = (Integer) request.getSession().getAttribute("managerid");
		String name = request.getParameter("name");
		String status = request.getParameter("tstatus");
		
//		String selectbut=request.getParameter("selectbut");
		int pageSize = 10;
		String fromDateStr = request.getParameter("fromDate");
		String endDateStr = request.getParameter("endDate");
		try {
			if (status!=null&&status.length() > 0) {
				status = URLDecoder.decode(URLDecoder.decode(status, "UTF-8"),"UTF-8");
			}
			if (name!=null&&name.length() > 0) {
				name = URLDecoder.decode(URLDecoder.decode(name, "UTF-8"),"UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
		}
		request.setAttribute("fromDate", fromDateStr);
		request.setAttribute("endDate", endDateStr);
		request.setAttribute("name", name);
		request.setAttribute("status", status);
		Long starttime = 0l;
		Long endtime = 0l;
		Date startDate = null;
		Date endDate = null;
		try {
			fromDateStr=fromDateStr+" 00:00:00";
			endDateStr=endDateStr+" 23:59:59";
			startDate = mdf.parse(fromDateStr);
			endDate = mdf.parse(endDateStr);
			starttime=startDate.getTime();
			endtime=endDate.getTime();
		} catch (Exception e) {
		}
		// 获取当前页数
		int currentPage = 1;
		try {
			currentPage = new Integer(request.getParameter("currentPage"));
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		int organizationid=(int) request.getSession().getAttribute("organizationid");
		boolean mp = managerService.selectPermissionsByCode(userid,"allApproveFile");
		if (mp) {
			int totalNum = maindataService.getAllMaindataListNum(name, status, starttime,endtime,organizationid, currentPage, pageSize);
			int totalPage = totalNum / pageSize;
			if (totalNum % pageSize != 0) {
				totalPage++;	
			}
			totalPage = totalPage <= 0 ? 1 : totalPage;
			currentPage = currentPage > totalPage ? totalPage : currentPage;
			List<TMaindata> list = maindataService.getAllMaindataList(name, status, starttime, endtime,organizationid, (currentPage - 1) * pageSize, pageSize);
			request.setAttribute("totalNum", totalNum);
			request.setAttribute("list", list);
			request.setAttribute("totalPage", totalPage);
		}else{
			int totalNum = maindataService.getMaindataListNumById(name, status, starttime,endtime,organizationid,0);
			int totalPage = totalNum / pageSize;
			if (totalNum % pageSize != 0) {
				totalPage++;	
			}
			totalPage = totalPage <= 0 ? 1 : totalPage;
			currentPage = currentPage > totalPage ? totalPage : currentPage;
			List<TMaindata> list = maindataService.getMaindataListById(name, status, starttime, endtime,organizationid, (currentPage - 1) * pageSize, pageSize,0);
			request.setAttribute("totalNum", totalNum);
			request.setAttribute("list", list);
			request.setAttribute("totalPage", totalPage);
		}
		//List<TUser> list=userService.selectTUserList(name, dept, starttime, endtime,jobnumber, (currentPage - 1) * pageSize, pageSize);
		Date Timestamp=new Date();
		request.setAttribute("Timestamp", Timestamp);
		//request.setAttribute("totalNum", totalNum);
		//request.setAttribute("list", list);
		request.setAttribute("currentPage", currentPage);
        //request.setAttribute("totalNum", totalNum);
        //request.setAttribute("totalPage", totalPage);
		return "approve/index";
	}
	/**
	 * App获取用户加班单位信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getUserUnits", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String getUserUnits(HttpServletRequest request, Model model) {
//		String sign=null;
		JSONObject jsonObject = null;
		String msg=null;
		String userid=null;
		String json = request.getParameter("json");
		jsonObject = JSONObject.fromObject(json);
		try{
//			sign =jsonObject.getString("sign");
			userid=jsonObject.getString("userid");
		}catch(Exception e){
            msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
//		TUser user=userService.selectTUserId(userid);
//		if (user == null) {
//			msg="{\"code\":\"3\",\"msg\":\"用户信息有误\"}";
//			return msg;
//		}
//		boolean judge=IdentityController.authentication(user, IdentityController.GETUSERUNITS, sign);
//		if(!judge){
//			msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//			return msg;
//		}
		List<TUserPay> userPay = userPayService.selectTUserPayListUserid(userid);
		msg = "{\"code\":\""+1+"\","
				+ "\"data\":{"
				+ "\"status\":\""+ userPay.get(0).getStatus() + "\","
	    		+ "\"type\":\"";
		
		int n=0;
		for (TUserPay tUserPay : userPay) {
			if(n==0){
				msg+=tUserPay.getType();
			}else{
				msg+=","+tUserPay.getType();
			}
			n++;
		}
		msg += "\""+"}}";
		return msg;
		
	}
	/**
	 * APP获取人员信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getUserDetail", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String getUserDetail(HttpServletRequest request, Model model) {
//		String sign=null;
		JSONObject jsonObject = null;
		String msg=null;
		String userid=null;
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		jsonObject = JSONObject.fromObject(json);
		try{
//			sign =jsonObject.getString("sign");
			userid=jsonObject.getString("userid");
		}catch(Exception e){
            msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
		TUser user=userService.selectTUserId(userid);
//		if (user == null) {
//			msg="{\"code\":\"3\",\"msg\":\"用户信息有误\"}";
//			return msg;
//		}
//		boolean judge=IdentityController.authentication(user, IdentityController.GETUSERDETAIL, sign);
//		if(!judge){
//			msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//			return msg;
//		}
//		TUser user=userService.selectTUserId(userid);
		//待审批
		int approveNum = maindataService.getNoHandleMaindataNum(userid, null, null);
		//抄送
		int recordNum = recordService.getIfHandleRecordNum(userid, null, null, null);
		//申请
		int applyNum = maindataService.getTMyApplyMaindataNum(userid, null , null, null);
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> datamap = new HashMap<>();
		map.put("code", "1");
		datamap.put("userid", user.getId());
		datamap.put("username", user.getName());
		datamap.put("approveNum", approveNum);
		datamap.put("recordNum", recordNum);
		datamap.put("applyNum", applyNum);
		datamap.put("companyName", user.getOrganization().getName());
		datamap.put("sex", user.getSex());
		datamap.put("position", user.getRole().getName());
		datamap.put("paylist", user.getPaylist());
		datamap.put("loginname", user.getLoginname());
		datamap.put("englishname", user.getEnglishname());
		datamap.put("jobnumber", user.getJobnumber());
		datamap.put("status", user.getStatus());
		datamap.put("whetheronline", user.getWhetheronline());
		datamap.put("logintime", user.getLogintime());
		datamap.put("organizationId", user.getOrganizationId());
		datamap.put("examineStatus", user.getExamineStatus());
		datamap.put("token", user.getToken());
		map.put("data", datamap);
		JSONObject jsonobj = JSONObject.fromObject(map);
		msg = jsonobj.toString();
		return msg;
	}
	/**
	 * APP获取审批详情信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getApproveDetail", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String getApproveDetail(HttpServletRequest request, Model model) {
//		String sign=null;
		JSONObject jsonObject = null;
		String msg=null;
//		String userid=null;
		String docid=null;
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		jsonObject = JSONObject.fromObject(json);
		try{
//			sign =jsonObject.getString("sign");
//			userid=jsonObject.getString("userid");
			docid=jsonObject.getString("docid");
		}catch(Exception e){
            msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
//		TUser user=userService.selectTUserId(userid);
//		if (user == null) {
//			msg="{\"code\":\"3\",\"msg\":\"用户信息有误\"}";
//			return msg;
//		}
//		boolean judge=IdentityController.authentication(user, IdentityController.GETAPPROVEDETAIL, sign);
//		if(!judge){
//			msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//			return msg;
//		}
		TMaindata maindata=maindataService.getMaindataById(docid);
		List<TRecord> list=recordService.getRecordListByApp(docid);
		
		int passstatus;
		if(maindata.getPassstatus()!=null){
			passstatus=maindata.getPassstatus();
		}else{
			passstatus=3;
		}
		//增加业务时，需要修改
		if(maindata.getType()!=null){
			if(maindata.getType()==1){
				List<TAttachmentStorage> storlist=attachmentStorageService.getTAttachmentStorageList(1,maindata.getLeave().getId());
	    		//请假
				msg = "{\"code\":\""+1+"\","
	    				+ "\"data\":{"
	    	    		+ "\"title\":\""+ maindata.getTitle() +"\","
	    	    		+ "\"status\":\""+ maindata.getStatus() +"\","
	    	    		+ "\"passstatus\":\""+ passstatus +"\","
	    	    		+ "\"userid\":\""+ maindata.getUserid() +"\","
	    	    	    + "\"username\":\""+ maindata.getUsername() +"\","
	    	    	    + "\"starttime\":\""+ maindata.getLeave().getStarttime() +"\","
	    	    	    + "\"endtime\":\""+ maindata.getLeave().getEndtime() +"\","
	    	    	    + "\"leaveday\":\""+ maindata.getLeave().getLeaveday() +"\","
	    	    	    + "\"leavetype\":\""+ maindata.getLeave().getType() +"\","
	    	    	    + "\"applytime\":\""+ maindata.getCreatetime() +"\","
	    	    	    + "\"description\":\""+ maindata.getLeave().getReason() +"\","
	    	    	    + "\"type\":\""+ maindata.getType() +"\","
	    	    		+ "\"pathlist\":[";
				int i=0;
	    	    for (TAttachmentStorage stor : storlist) {
	    	    	String path=null;
	    	    	if(stor.getPath().indexOf("/")>-1){
	    	    		path=stor.getPath().substring(stor.getPath().indexOf("/")+1,stor.getPath().length());
	    	    	}else{
	    	    		path=stor.getPath();
	    	    	}
	    	    	i++;
	    	    	msg += "{\"path\":\"" + ServiceConfig.webServiceUrl+path + "\","
	    					+ "\"type\":\""+ stor.getType()+ "\","
	    					+ "\"name\":\""+ stor.getName()+ "\""
	    					+ "}";
	    	    	if(i<storlist.size()){
	    	    		msg+=",";
	    	    	}
				}
	    	    msg+="],"
						+ "\"wanderlist\":[";
	    	}else if(maindata.getType()==2){
	    		//加班 
	    		msg = "{\"code\":\""+1+"\","
	    				+ "\"data\":{"
	    	    		+ "\"title\":\""+ maindata.getTitle() +"\","
	    	    		+ "\"status\":\""+ maindata.getStatus() +"\","
	    	    		+ "\"passstatus\":\""+ passstatus +"\","
	    	    		+ "\"userid\":\""+ maindata.getUserid() +"\","
	    	    	    + "\"username\":\""+ maindata.getUsername() +"\","
	    	    	    + "\"starttime\":\""+ maindata.getOvertime().getStarttime() +"\","
	    	    	    + "\"number\":\""+ maindata.getOvertime().getNumber() +"\","
	    	    	    + "\"unit\":\""+ maindata.getOvertime().getUnit() +"\","
	    	    	    + "\"applytime\":\""+ maindata.getCreatetime() +"\","
	    	    	    + "\"description\":\""+ maindata.getOvertime().getOvertimereason() +"\","
	    	    	    + "\"type\":\""+ maindata.getType() +"\","
	    	    		+ "\"wanderlist\":[";
	    	}else if(maindata.getType()==3){
	    		//通用
	    		List<TAttachmentStorage> storlist=attachmentStorageService.getTAttachmentStorageList(2,maindata.getEncy().getId());
	    		msg = "{\"code\":\""+1+"\","
	    				+ "\"data\":{"
	    	    		+ "\"title\":\""+ maindata.getTitle() +"\","
	    	    		+ "\"status\":\""+ maindata.getStatus() +"\","
	    	    		+ "\"passstatus\":\""+ passstatus +"\","
	    	    		+ "\"userid\":\""+ maindata.getUserid() +"\","
	    	    	    + "\"username\":\""+ maindata.getUsername() +"\","
	    	    	    + "\"content\":\""+ maindata.getEncy().getContent() +"\","
	    	    	    + "\"remark\":\""+ maindata.getEncy().getRemark() +"\","
	    	    	    + "\"applytime\":\""+ maindata.getCreatetime() +"\","
	    	    	    + "\"description\":\""+ maindata.getEncy().getDetails() +"\","
	    	    	    + "\"type\":\""+ maindata.getType() +"\","
	    	    	    + "\"pathlist\":[";
	    		int i=0;
	    		for (TAttachmentStorage stor : storlist) {
	    	    	String path=null;
	    	    	if(stor.getPath().indexOf("/")>-1){
	    	    		path=stor.getPath().substring(stor.getPath().indexOf("/")+1,stor.getPath().length());
	    	    	}else{
	    	    		path=stor.getPath();
	    	    	}
	    	    	i++;
	    	    	msg += "{\"path\":\"" + ServiceConfig.webServiceUrl+path + "\","
	    	    			+ "\"type\":\""+ stor.getType()+ "\","
	    					+ "\"name\":\""+ stor.getName()+ "\""
	    					+ "}";
	    	    	if(i<storlist.size()){
	    	    		msg+=",";
	    	    	}
				}
	    	    msg+="],"
	    	    		+ "\"wanderlist\":[";
	    	}else if(maindata.getType()==4){
	    		//借钱
	    		msg = "{\"code\":\""+1+"\","
	    				+ "\"data\":{"
	    	    		+ "\"title\":\""+ maindata.getTitle() +"\","
	    	    		+ "\"status\":\""+ maindata.getStatus() +"\","
	    	    		+ "\"passstatus\":\""+ passstatus +"\","
	    	    		+ "\"userid\":\""+ maindata.getUserid() +"\","
	    	    	    + "\"username\":\""+ maindata.getUsername() +"\","
	    	    	    + "\"money\":\""+ maindata.getBorrow().getMoney() +"\","
	    	    	    + "\"borrowingtime\":\""+ maindata.getBorrow().getBorrowingtime() +"\","
	    	    	    + "\"returntime\":\""+ maindata.getBorrow().getReturntime() +"\","
	    	    	    + "\"applytime\":\""+ maindata.getCreatetime() +"\","
	    	    	    + "\"reason\":\""+ maindata.getBorrow().getReason() +"\","
	    	    	    + "\"description\":\""+ maindata.getBorrow().getRemark() +"\","
	    	    	    + "\"type\":\""+ maindata.getType() +"\","
	    	    		+ "\"wanderlist\":[";
	    	}else if(maindata.getType()==5){
	    		//补卡
	    		msg = "{\"code\":\""+1+"\","
	    				+ "\"data\":{"
	    	    		+ "\"title\":\""+ maindata.getTitle() +"\","
	    	    		+ "\"status\":\""+ maindata.getStatus() +"\","
	    	    		+ "\"passstatus\":\""+ passstatus +"\","
	    	    		+ "\"userid\":\""+ maindata.getUserid() +"\","
	    	    	    + "\"username\":\""+ maindata.getUsername() +"\","
	    	    	    + "\"filltime\":\""+ maindata.getFill().getFilltime() +"\","
	    	    	    + "\"filltype\":\""+ maindata.getFill().getType() +"\","
	    	    	    + "\"attendanceid\":\""+ maindata.getFill().getAttendanceid() +"\","
	    	    	    + "\"applytime\":\""+ maindata.getCreatetime() +"\","
	    	    	    + "\"type\":\""+ maindata.getType() +"\","
	    	    	    + "\"description\":\""+ maindata.getFill().getRemark() +"\","
	    	    		+ "\"wanderlist\":[";
	    	}
		}else{
			msg="{\"code\":\"2\",\"msg\":\"业务类型不存在\"}";
			return msg;
		}
    	
	    int n = 0;
	    for(TRecord record:list){
	    	if (n > 0) {
				msg += ",";
			}
	    	
	    	int remarktype;
	    	if(record.getRemarktype()!=null){
	    		remarktype=record.getRemarktype();
	    	}else{
	    		remarktype=3;
	    	}
	    	if(n==0){
	    		remarktype=4;
	    	}
	    	String remark="";
	    	if(record.getRemark()!=null){
	    		remark=record.getRemark();
	    	}
	    	n++;
	    	msg += "{\"recordid\":\"" + record.getId() + "\","
					+ "\"uid\":\""+ record.getUserid()+ "\","
					+ "\"uname\":\"" + record.getUsername()+ "\"," 
					+ "\"handletime\":\""+ record.getEndtime() + "\","
					+ "\"remark\":\""+ remark + "\","
					+ "\"remarktype\":\""+ remarktype + "\""
					+ "}";
	    }
	    msg += "]}}";
		return msg;
	}
	/**
	 * APP获取审批人或抄送人列表信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getUserList", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String getUserList(HttpServletRequest request, Model model) {
//		String sign=null;
		JSONObject jsonObject = null;
		String msg=null;
		String userid=null;
		Integer orgid = null;
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		jsonObject = JSONObject.fromObject(json);
		try{
//			sign =jsonObject.getString("sign");
			userid=jsonObject.getString("userid");
			orgid = jsonObject.getInt("organizationid");
		}catch(Exception e){
            msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
		//判断用户信息
//		TUser user=userService.selectTUserId(userid);
//		if (user == null) {
//			msg="{\"code\":\"3\",\"msg\":\"用户信息有误\"}";
//			return msg;
//		}
//		boolean judge=IdentityController.authentication(user, IdentityController.GETUSERLIST, sign);
//		if(!judge){
//			msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//			return msg;
//		}
		List<TUser> list=userBeanService.getAllUserListByApp(orgid,userid);
		msg = "{\"code\":" +1+"," 
				+"\"data\":{"
	    		+"\"userlist\":[";
	    int n = 0;
	    for(TUser u:list){
	    	if (n > 0) {
				msg += ",";
			}
	    	n++;
	    	msg += "{\"userid\":" + u.getId() + ","
					+ "\"username\":\""+ u.getName()+ "\""
					+ "}";
	    }
	    msg += "]}}";
		return msg;
	}
	/**
	 * APP获取审批列表信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getApproveList", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String getApproveList(HttpServletRequest request, Model model) {
		int pageSize = 10;
		String type=null;
		String msg=null;
		String userid=null;
		String doctype=null;
		String status=null;
		String searchStr=null;
		String currentPageStr=null;
		String handleStatus=null;//审批： 1：待审批，2：已批 ；，抄送：1：未读，2:已读，3:全部   我发送：3
		JSONObject jsonObject = null;
//		String sign=null;
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		jsonObject = JSONObject.fromObject(json);
		try{
			type =jsonObject.getString("type");
			userid =jsonObject.getString("userid");
			doctype =jsonObject.getString("doctype");
			status =jsonObject.getString("status");
			searchStr =jsonObject.getString("searchStr");
//			sign =jsonObject.getString("sign");
			currentPageStr =jsonObject.getString("currentPage");
			handleStatus=jsonObject.getString("handleStatus");
		}catch(Exception e){
            msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
		//判断用户信息
//		TUser user=userService.selectTUserId(userid);
//		if (user == null) {
//			msg="{\"code\":\"3\",\"msg\":\"用户信息有误\"}";
//			return msg;
//		}
//		boolean judge=IdentityController.authentication(user, IdentityController.GETAPPROVELIST, sign);
//		if(!judge){
//			msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//			return msg;
//		}
		// 获取当前页数
		int currentPage = 1;
		try {
			if(currentPageStr!=null && currentPageStr!=""){
				currentPage = Integer.parseInt(currentPageStr);
			}
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		//查询数据
		//我申请的  ：type=1   type=2 : 我审批     type=3 : 抄送
		if(type!=null && type!=""){
			if("1".equals(type)){
				int totalNum = maindataService.getTMyApplyMaindataNum(userid, doctype, status, searchStr);
				int totalPage = totalNum / pageSize;
				if (totalNum % pageSize != 0) {
					totalPage++;	
				}
				totalPage = totalPage <= 0 ? 1 : totalPage;
				currentPage = currentPage > totalPage ? totalPage : currentPage;
				List<TMaindata> list=maindataService.getTMyApplyMaindataList(userid, doctype, status, searchStr, (currentPage - 1) * pageSize, pageSize);
				msg = "{\"code\":" +1+"," 
						+"\"data\":{"
						+"\"total\":" +totalNum +"," 
			    		+ "\"currentPage\":"+ currentPage+","
			    		+ "\"pageSize\":"+ pageSize+","
			    		+"\"approvelist\":[";
			    int n = 0;
			    for(TMaindata maindata:list){
			    	if (n > 0) {
						msg += ",";
					}
			    	n++;
			    	//增加业务时，需要修改
			    	String description="";
			    	if(maindata.getLeave().getReason()!=null&&maindata.getLeave().getReason()!=""){
			    		description=maindata.getLeave().getReason();
			    	}else if(maindata.getOvertime().getOvertimereason()!=null&&maindata.getOvertime().getOvertimereason()!=""){
			    		description=maindata.getOvertime().getOvertimereason();
			    	}else if(maindata.getFill().getRemark()!=null&&maindata.getFill().getRemark()!=""){
			    		description=maindata.getFill().getRemark();
			    	}else if(maindata.getBorrow().getReason()!=null&&maindata.getBorrow().getReason()!=""){
			    		description=maindata.getBorrow().getReason();
			    	}else if(maindata.getEncy().getDetails()!=null&&maindata.getEncy().getDetails()!=""){
			    		description=maindata.getEncy().getDetails();
			    	}
			    	msg += "{\"docid\":" + maindata.getId() + ","
							+ "\"bussineeid\":\""+ maindata.getBusinessid()+ "\","
							+ "\"title\":\"" + maindata.getTitle()+ "\"," 
							+ "\"status\":\""+ maindata.getStatus() + "\","
							+ "\"passstatus\":\""+ maindata.getPassstatus() + "\","
							+ "\"applytime\":\""+ maindata.getCreatetime() + "\","
							+ "\"description\":\""+ description + "\","
							+ "\"type\":\""+ maindata.getType() + "\""
							+ "}";
			    }
			    msg += "]}}";
			}else if("2".equals(type)){
				//审批
				int totalNum = 0;
				if("1".equals(handleStatus)){
					//待审批
					totalNum = maindataService.getNoHandleMaindataNum(userid, doctype, searchStr);
				}else if("2".equals(handleStatus)){
					//已审批
					totalNum = maindataService.getYesHandleMaindataNum(userid, doctype, searchStr);
				}
				int totalPage = totalNum / pageSize;
				if (totalNum % pageSize != 0) {
					totalPage++;	
				}
				totalPage = totalPage <= 0 ? 1 : totalPage;
				currentPage = currentPage > totalPage ? totalPage : currentPage;
				List<TMaindata> list=null;
				if("1".equals(handleStatus)){
					list=maindataService.getNOHandleMaindataList(userid, doctype, searchStr, (currentPage - 1) * pageSize, pageSize);
				}else if("2".equals(handleStatus)){
					list=maindataService.getYesHandleMaindataList(userid, doctype, searchStr, (currentPage - 1) * pageSize, pageSize);
				}else{
					//list=maindataService.getYesHandleMaindataList(userid, doctype, searchStr, (currentPage - 1) * pageSize, pageSize);
				}
				msg = "{\"code\":" +1+"," 
						+"\"data\":{"
						+"\"total\":" +totalNum +"," 
			    		+ "\"currentPage\":"+ currentPage+","
			    		+ "\"pageSize\":"+ pageSize+","
			    		+"\"approvelist\":[";
			    int n = 0;
			    for(TMaindata maindata:list){
			    	if (n > 0) {
						msg += ",";
					}
			    	n++;
			    	//增加业务时，需要修改
			    	String description="";
			    	if(maindata.getLeave().getReason()!=null&&maindata.getLeave().getReason()!=""){
			    		description=maindata.getLeave().getReason();
			    	}else if(maindata.getOvertime().getOvertimereason()!=null&&maindata.getOvertime().getOvertimereason()!=""){
			    		description=maindata.getOvertime().getOvertimereason();
			    	}else if(maindata.getFill().getRemark()!=null&&maindata.getFill().getRemark()!=""){
			    		description=maindata.getFill().getRemark();
			    	}else if(maindata.getBorrow().getReason()!=null&&maindata.getBorrow().getReason()!=""){
			    		description=maindata.getBorrow().getReason();
			    	}else if(maindata.getEncy().getDetails()!=null&&maindata.getEncy().getDetails()!=""){
			    		description=maindata.getEncy().getDetails();
			    	}
			    	int passstatus=0;
			    	if(maindata.getPassstatus()==null){
			    		passstatus=3;
			    	}else{
			    		passstatus=maindata.getPassstatus();
			    	}
			    	msg += "{\"docid\":" + maindata.getId() + ","
							+ "\"bussineeid\":\""+ maindata.getBusinessid()+ "\","
							+ "\"title\":\"" + maindata.getTitle()+ "\"," 
							+ "\"status\":\""+ maindata.getStatus() + "\","
							+ "\"passstatus\":\""+ passstatus + "\","
							+ "\"applytime\":\""+ maindata.getCreatetime() + "\","
							+ "\"description\":\""+ description + "\","
							+ "\"type\":\""+ maindata.getType() + "\""
							+ "}";
			    }
			    msg += "]}}";
			}else if("3".equals(type)){
				//抄送
				int totalNum = recordService.getIfHandleRecordNum(userid, doctype, handleStatus, searchStr);
				int totalPage = totalNum / pageSize;
				if (totalNum % pageSize != 0) {
					totalPage++;	
				}
				totalPage = totalPage <= 0 ? 1 : totalPage;
				currentPage = currentPage > totalPage ? totalPage : currentPage;
				List<TRecord> list=recordService.getIfHandleRecordList(userid, doctype, handleStatus, searchStr, (currentPage - 1) * pageSize, pageSize);
				msg = "{\"code\":" +1+"," 
						+"\"data\":{"
						+"\"total\":" +totalNum +"," 
			    		+ "\"currentPage\":"+ currentPage+","
			    		+ "\"pageSize\":"+ pageSize+","
			    		+"\"approvelist\":[";
			    int n = 0;
			    for(TRecord TRecord:list){
			    	if (n > 0) {
						msg += ",";
					}
			    	n++;
			    	//增加业务时，需要修改
			    	String description="";
			    	if(TRecord.getLeave().getReason()!=null&&TRecord.getLeave().getReason()!=""){
			    		description=TRecord.getLeave().getReason();
			    	}else if(TRecord.getOvertime().getOvertimereason()!=null&&TRecord.getOvertime().getOvertimereason()!=""){
			    		description=TRecord.getOvertime().getOvertimereason();
			    	}else if(TRecord.getFill().getRemark()!=null&&TRecord.getFill().getRemark()!=""){
			    		description=TRecord.getFill().getRemark();
			    	}else if(TRecord.getBorrow().getReason()!=null&&TRecord.getBorrow().getReason()!=""){
			    		description=TRecord.getBorrow().getReason();
			    	}else if(TRecord.getEncy().getDetails()!=null&&TRecord.getEncy().getDetails()!=""){
			    		description=TRecord.getEncy().getDetails();
			    	}
			    	msg += "{\"docid\":" + TRecord.getMaindata().getId() + ","
							+ "\"bussineeid\":\""+ TRecord.getMaindata().getBusinessid()+ "\","
							+ "\"title\":\"" + TRecord.getMaindata().getTitle()+ "\"," 
							+ "\"status\":\""+ TRecord.getMaindata().getStatus() + "\","
							+ "\"passstatus\":\""+ TRecord.getMaindata().getPassstatus() + "\","
							+ "\"applytime\":\""+ TRecord.getMaindata().getCreatetime() + "\","
							+ "\"description\":\""+ description + "\","
							+ "\"type\":\""+ TRecord.getMaindata().getType() + "\""
							+ "}";
			    }
			    msg += "]}}";
			}
		}else{
			msg="{\"code\":\"2\",\"msg\":\"类型参数不能为空\"}";
		}
		return msg;
	}
	/**
	 * APP审批提交
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/saveApprove", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String saveApprove(HttpServletRequest request, Model model) {
		String msg=null;
		Long createtime=new Date().getTime();
		JSONObject jsonObject = null;
//		String sign =null;
		String userid=null;
		String username=null;
		String approvetype=null;
		String approvename=null;
		JSONArray authorArray =null;
		JSONArray copyuserArray =null;
		int organizationid=0;
		JSONObject dataObject;
		//要保存字段
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		jsonObject = JSONObject.fromObject(json);
		try{
//			sign =jsonObject.getString("sign");
			userid =jsonObject.getString("userid");
			username =jsonObject.getString("username");
			approvetype =jsonObject.getString("approvetype");
			approvename =jsonObject.getString("approvename");
			organizationid =jsonObject.getInt("organizationid");
			authorArray=jsonObject.getJSONArray("authorlist");
			copyuserArray=jsonObject.getJSONArray("copyuserlist");
			String dataList=jsonObject.getString("datalist");
			dataObject=JSONObject.fromObject(dataList);
			username=java.net.URLDecoder.decode(username,"UTF-8");
			approvename=java.net.URLDecoder.decode(approvename,"UTF-8");
		}catch(Exception e){
            msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
		//判断用户信息
//		TUser user=userService.selectTUserId(userid);
//		if (user == null) {
//			msg="{\"code\":\"3\",\"msg\":\"用户信息有误\"}";
//			return msg;
//		}
//		boolean judge=IdentityController.authentication(user, IdentityController.SAVEAPPROVE, sign);
//		if(!judge){
//			msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//			return msg;
//		}
		int fal=0;
		int businessid=0;
		if("1".equals(approvetype) && approvetype!=null){
			//请假
			TLeave leave=new TLeave();
			try{
				leave.setUserid(Integer.parseInt(userid));
				leave.setUsername(username);
				leave.setType(Integer.parseInt(dataObject.getString("type")));
				leave.setStarttime(Long.parseLong(dataObject.getString("starttime")));
				leave.setEndtime(Long.parseLong(dataObject.getString("endtime")));
//				leave.setIfsalary(Integer.parseInt(dataObject.getString("ifsalary")));
				leave.setLeaveday(Double.parseDouble(dataObject.getString("leaveday")));
				leave.setReason(dataObject.getString("reason"));
				leave.setCreatetime(createtime);
			}catch(Exception e){
	            msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
	            return msg;
			}
			fal=leaveService.insertTLeave(leave);
			businessid=leave.getId();
			try{
				String pathlists=dataObject.getString("pathlist");
				JSONArray pathlist = JSONArray.fromObject(pathlists ); 
				if(pathlist.size()>0){
					List<TAttachmentStorage> agelist=new ArrayList<TAttachmentStorage>(); 
					for(int i=0;i<pathlist.size();i++){
						JSONObject job = pathlist.getJSONObject(i); 
						TAttachmentStorage age=new TAttachmentStorage();
						age.setBusinessid(leave.getId());
						age.setBusinesstype(1);
						age.setType(job.getInt("type"));
						age.setPath(job.getString("path"));
						age.setName(job.getString("name"));
						agelist.add(age);
					}
					if(agelist!=null&&agelist.size()>0){
						attachmentStorageService.insertAttachmentStorageList(agelist);
					}
				}
			}catch(Exception e){
				
				msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
				return msg;
			}
		}else if("2".equals(approvetype) && approvetype!=null){
			//加班
			TOvertime overtime=new TOvertime();
			try{
				overtime.setUserid(Integer.parseInt(userid));
				overtime.setUsername(username);
				overtime.setType(dataObject.getInt("type"));
				overtime.setStarttime(Long.parseLong(dataObject.getString("starttime")));
				overtime.setNumber(Double.parseDouble(dataObject.getString("number")));
				overtime.setUnit(Integer.parseInt(dataObject.getString("unit")));
				overtime.setOvertimereason(java.net.URLDecoder.decode(dataObject.getString("overtimereason")));
				overtime.setCreatetime(createtime);
			}catch(Exception e){
	            msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
	            return msg;
			}
			fal=overtimeService.insertTOvertime(overtime);
			businessid=overtime.getId();
		}else if("3".equals(approvetype) && approvetype!=null){
			//通用
			TCurrency currency = new TCurrency();
			try {
				currency.setUserid(Integer.parseInt(userid));
				currency.setUsername(username);
				currency.setContent(java.net.URLDecoder.decode(dataObject.getString("content")));
				currency.setDetails(java.net.URLDecoder.decode(dataObject.getString("details")));
				currency.setRemark(java.net.URLDecoder.decode(dataObject.getString("remark")));
				currency.setCreatetime(createtime);
			} catch (Exception e) {
				 msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
		         return msg;
			}
			fal=currencyService.insertCurrencyService(currency);
			businessid = currency.getId();
			try{
				String pathlists=dataObject.getString("pathlist");
				JSONArray pathlist = JSONArray.fromObject(pathlists ); 
				if(pathlist.size()>0){
					List<TAttachmentStorage> agelist=new ArrayList<TAttachmentStorage>(); 
					for(int i = 0; i < pathlist.size(); i++) {
						JSONObject object = (JSONObject) pathlist.get(i);
						TAttachmentStorage age=new TAttachmentStorage();
						age.setBusinessid(currency.getId());
						age.setBusinesstype(2);
						age.setType(object.getInt("type"));
						age.setPath(object.getString("path"));
						age.setName(object.getString("name"));
						agelist.add(age);
					}
					if(agelist!=null&&agelist.size()>0){
						attachmentStorageService.insertAttachmentStorageList(agelist);
					}
				}
			}catch(Exception e){
				msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
				return msg;
			}
		}else if("4".equals(approvetype) && approvetype!=null){
			//借钱
			TBorrow borrow = new TBorrow();
			try {
				borrow.setUserid(Integer.parseInt(userid));
				borrow.setUsername(username);
				borrow.setMoney(dataObject.getDouble("money"));
				borrow.setRemark(dataObject.getString("remark"));
				borrow.setBorrowingtime(dataObject.getLong("borrowingtime"));
				borrow.setReturntime(dataObject.getLong("returntime"));
				borrow.setReason(dataObject.getString("reason"));
				borrow.setCreatetime(createtime);
			} catch (Exception e) {
				msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
		         return msg;
			}
			fal = borrowService.insertBorrow(borrow);
			businessid = borrow.getId();
		}else if("5".equals(approvetype) && approvetype!=null){
			//补卡
			TFillcard fill = new TFillcard();
			try {
				fill.setUserid(Integer.parseInt(userid));
				fill.setUsername(username);
				fill.setFilltime(dataObject.getLong("filltime"));
				fill.setAttendanceid(dataObject.getInt("attendanceid"));
				fill.setType(dataObject.getInt("type"));
				fill.setRemark(dataObject.getString("remark"));
				fill.setDetailsid(dataObject.getInt("detailsid"));
				fill.setCreatetime(createtime);
			} catch (Exception e) {
				msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
		         return msg;
			}
			fal = fillcardService.insertTFillcard(fill);
			businessid = fill.getId();
		}
		if(fal>0){
			//生成业务表成功
			msg="sussce";
			//生成实例表
			TMaindata maindata=new TMaindata();
			maindata.setOrganizationId(organizationid);
			maindata.setBusinessid(businessid);
			maindata.setTitle(username+"的"+approvename+"申请");
			maindata.setType(Integer.parseInt(approvetype));
			maindata.setName(approvename);
			maindata.setCreatetime(createtime);
			maindata.setUserid(Integer.parseInt(userid));
			maindata.setUsername(username);
			maindata.setMidifytime(createtime);
			//审批者
			maindata.setAuthorid(Integer.parseInt(authorArray.getJSONObject(0).getString("uid")));
			maindata.setAuthorname(authorArray.getJSONObject(0).getString("uname"));
			//maindata.setEnduser(authorArray.getJSONObject(0).getString("uid"));
			maindata.setAllreaders("1,2,"+userid+","+authorArray.getJSONObject(0).getString("uid"));
			String copyuseridstr="";
			for(int i=0;i<copyuserArray.size();i++){
                JSONObject copyuserObject=copyuserArray.getJSONObject(i);
                if(copyuserArray.size()==1){
                	copyuseridstr = copyuseridstr+copyuserObject.getString("uid");
                }else if(copyuserArray.size()>1){
                	if(copyuserArray.size()-1==i){
                		copyuseridstr = copyuseridstr+copyuserObject.getString("uid");
                	}else{
                		copyuseridstr = copyuseridstr+copyuserObject.getString("uid")+",";
                	}
                }
            }
			maindata.setCopyuser(copyuseridstr);
			maindata.setStatus(1);
			int faldata=maindataService.insertTMaindata(maindata);
			if(faldata>0){
				msg+="mainsussce";
				int docunid=maindata.getId();
				int m=1;
				//生成审批记录表
				for(int i=0;i<authorArray.size();i++){
					TRecord record=new TRecord();
					JSONObject authorObject=authorArray.getJSONObject(i);
					record.setDocunid(docunid);
					record.setBusinessid(businessid);
					record.setCreatetime(createtime);
					record.setMidifytime(createtime);
					if(i==0){
						record.setUserid(Integer.parseInt(userid));
						record.setUsername(username);
						record.setFactuserid(Integer.parseInt(userid));
						record.setFactusername(username);
						record.setStarttime(createtime);
						record.setEndtime(createtime);
						record.setNextuserid(Integer.parseInt(authorObject.getString("uid")));
						record.setNextusername(authorObject.getString("uname"));
						record.setDocstatus(3);
						record.setHandlestatus(1);
					}else if(i>0){
						
						record.setUserid(Integer.parseInt(authorArray.getJSONObject(i-1).getString("uid")));
						record.setUsername(authorArray.getJSONObject(i-1).getString("uname"));
						record.setNextuserid(Integer.parseInt(authorObject.getString("uid")));
						record.setNextusername(authorObject.getString("uname"));
						if(i==1){
							record.setDocstatus(1);
							record.setStarttime(createtime);
						}else if(i>1){
							record.setDocstatus(2);
						}
						record.setHandlestatus(2);
					}
					record.setNodestatus(1);
					record.setRecordtype(1);
					record.setNodesort(m);
					int falrec=recordService.insertTRecord(record);
					if(falrec>0){
						msg="{\"code\":\"1\",\"msg\":\"提交审批成功\"}";
						m++;
					}else{
						msg="{\"code\":\"2\",\"msg\":\"实例记录数据生成失败\"}";
					}
	            }
				//保存最后节点的处理记录数据
				TRecord record=new TRecord();
				JSONObject authorlastObject=authorArray.getJSONObject((authorArray.size()-1));
				record.setDocunid(docunid);
				record.setBusinessid(businessid);
				record.setCreatetime(createtime);
				record.setUserid(Integer.parseInt(authorlastObject.getString("uid")));
				record.setUsername(authorlastObject.getString("uname"));
				record.setHandlestatus(2);
				record.setNodesort(m);
				record.setNodestatus(2);
				record.setRecordtype(1);
				if(authorArray.size()==1){
					record.setStarttime(createtime);
					record.setDocstatus(1);
				}else{
					record.setDocstatus(2);
				}
				int falrec=recordService.insertTRecord(record);
				if(falrec>0){
					msg="{\"code\":\"1\",\"msg\":\"提交审批成功\"}";
				}else{
					msg="{\"code\":\"2\",\"msg\":\"实例审批记录数据生成失败\"}";
				}
				//生成抄送记录数据
				for(int i=0;i<copyuserArray.size();i++){
					JSONObject copyuserObject=copyuserArray.getJSONObject(i);
					TRecord recordcopy=new TRecord();
					recordcopy.setDocunid(docunid);
					recordcopy.setBusinessid(businessid);
					recordcopy.setUserid(Integer.parseInt(copyuserObject.getString("uid")));
					recordcopy.setUsername(copyuserObject.getString("uname"));
					recordcopy.setDocstatus(2);
					recordcopy.setRecordtype(2);
					recordcopy.setHandlestatus(2);
					recordcopy.setMidifytime(createtime);
					recordcopy.setCreatetime(createtime);
					recordcopy.setStarttime(createtime);
					int falcopy=recordService.insertTRecord(recordcopy);
					if(falcopy>0){
						msg="{\"code\":\"1\",\"msg\":\"提交审批成功\"}";
					}else{
						msg="{\"code\":\"2\",\"msg\":\"实例抄送记录数据生成失败\"}";
					}
				}
			}else{
				msg="{\"code\":\"2\",\"msg\":\"实例数据生成失败\"}";
			}
		}else{
			msg="{\"code\":\"2\",\"msg\":\"业务数据生成失败\"}";
		}
		return msg;
	}
	
	
	
	/**
	 * APP审批办理
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/handleApprove", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String handleApprove(HttpServletRequest request, Model model) {
		String msg=null;
		long handletime=new Date().getTime();
		JSONObject jsonObject = null;
//		String sign =null;
		String userid =null;
		String username=null;
		String docunid=null;
		String recordtype=null;
		String remarktype=null;
		String remark=null;		
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		jsonObject = JSONObject.fromObject(json);
		try{
			userid =jsonObject.getString("userid");
//			sign =jsonObject.getString("sign");
			docunid =jsonObject.getString("docunid");
			recordtype =jsonObject.getString("recordtype");
			username=jsonObject.getString("username");
			if("1".equals(recordtype)){
				remarktype =jsonObject.getString("remarktype");
				remark =java.net.URLDecoder.decode(jsonObject.getString("remark"));
			}
		}catch(Exception e){
            msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
		//判断用户信息
//		TUser user=userService.selectTUserId(userid);
//		if (user == null) {
//			msg="{\"code\":\"3\",\"msg\":\"用户信息有误\"}";
//			return msg;
//		}
//		boolean judge=IdentityController.authentication(user, IdentityController.HANDLEAPPROVE, sign);
//		if(!judge){
//			msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//			return msg;
//		}
		//查询实例数据 by id 
		TMaindata maindata=maindataService.selectTMaindataById(docunid);
		//查询审批记录数据  by 实例id,记录状态,userid
		TRecord record=recordService.selectTRecordByDocunid(docunid, userid, recordtype);
		if(maindata!=null && record!=null){
			if(record.getRecordtype()==1){
				//审批
				if(record.getNodestatus()==1){
					//不是最后一个节点
					//更新当前记录数据的状态以及启动下个节点。
					int nodesort = record.getNodesort()+1;
					//通过节点路径查询 实例id  与    记录数据  
					TRecord nextRecord = recordService.getTRecordByDidAndSort(docunid, String.valueOf(nodesort));
					//update  record
					record.setEndtime(handletime);
					record.setMidifytime(handletime);
					//实际审批人
					record.setFactuserid(Integer.parseInt(userid));
					record.setFactusername(username);
					record.setDocstatus(3);
					record.setHandlestatus(1);
					if(remarktype!=null && remarktype!="" && !"".equals(remarktype)){
						record.setRemarktype(Integer.parseInt(remarktype));
					}
					if(remark!=null && remark!=null && !"".equals(remarktype)){
						record.setRemark(remark);
					}
					int falre=recordService.updateTRecord(record);
					if(falre>0){
						//判断是否同意审批 ，如果是不同意就结束流程。
						if(record.getRemarktype()==1){
							//同意//update  nextRecord
							nextRecord.setDocstatus(1);
							nextRecord.setStarttime(handletime);
							int falren=recordService.updateTRecord(nextRecord);
							if(falren>0){
								msg="{\"code\":\"1\",\"msg\":\"审批办理成功\"}";
							}else{
								msg="{\"code\":\"2\",\"msg\":\"审批办理失败\"}";
							}
							maindata.setAuthorid(record.getNextuserid());
							maindata.setAuthorname(record.getNextusername());
							String allreaders=maindata.getAllreaders()+","+nextRecord.getUserid();
							maindata.setAllreaders(allreaders);
						}else if(record.getRemarktype()==2){
							//不同意
							maindata.setStatus(2);
							maindata.setPassstatus(2);
						}
						//update maindata
						maindata.setMidifytime(handletime);
						String enduser=maindata.getEnduser();
						if(enduser!=null){
							enduser=enduser+","+record.getUserid();
						}else{
							enduser=record.getUserid()+"";
						}
						//maindata.setEnduser(enduser);
						int falm=maindataService.updateTMaindata(maindata);
						if(falm>0){
							msg="{\"code\":\"1\",\"msg\":\"审批办理成功\"}";
						}else{
							msg="{\"code\":\"2\",\"msg\":\"审批办理失败\"}";
						}
					}else{
						msg="{\"code\":\"2\",\"msg\":\"审批办理失败\"}";
					}
				}else if(record.getNodestatus()==2){
					//最后节点
					//update  record
					record.setDocstatus(3);
					record.setHandlestatus(1);
					record.setEndtime(handletime);
					record.setMidifytime(handletime);
					//实际审批人
					record.setFactuserid(Integer.parseInt(userid));
					record.setFactusername(username);
					if(remarktype!=null && remarktype!="" && !"".equals(remarktype)){
						record.setRemarktype(Integer.parseInt(remarktype));
					}
					if(remark!=null && remark!=null && !"".equals(remarktype)){
						record.setRemark(remark);
					}
					int falre=recordService.updateTRecord(record);
					if(falre>0){
						//已归档
						//update maindata
						maindata.setMidifytime(handletime);
						maindata.setEndtime(handletime);
						maindata.setStatus(2);
						String enduser=maindata.getEnduser();
						if(enduser!=null){
							enduser=enduser+","+record.getUserid();
						}else{
							enduser=record.getUserid()+"";
						}
						maindata.setEnduser(enduser);
						if(record.getRemarktype()==1){
							maindata.setPassstatus(1);
						}else if(record.getRemarktype()==2){
							maindata.setPassstatus(2);
						}
						int falm=maindataService.updateTMaindata(maindata);
						if(falm>0){
							//归档操作
							//判断是否存在抄送，如无：直接归档，否则等待抄送已读后归档
							int num=recordService.getRecordCopyNum(docunid);
							maindataService.updateTMaindata(maindata);
							if(num>0){
								//存在抄送，不归档   启动抄送状态
								int falc=recordService.updateTRecordCopyStatus(docunid,String.valueOf(handletime));
								if(falc>0){
									msg="{\"code\":\"1\",\"msg\":\"审批办理成功,存在抄送,未归档\"}";
								}
							}else{
								//不存在抄送，归档
								msg="{\"code\":\"1\",\"msg\":\"审批办理成功,已归档\"}";
							}
							//验证业务类型
							TUser userbiss=new TUser();
							if(maindata.getType()==1){//请假
								TLeave leave=leaveService.getTLeaveById(maindata.getBusinessid());
								if(leave!=null){
									userbiss=userService.selectTUserId(String.valueOf(leave.getUserid()));
									List<TClocktime> clolist=clocktimeService.getTClocktimeByTime(leave.getStarttime(), leave.getEndtime(), userbiss.getSchedulingId());
									List<TAttendance> newattlist=new ArrayList<TAttendance>();
									List<TAttendance> updateattlist=new ArrayList<TAttendance>();
									if(clolist!=null){
										setLesveAttendance(clolist, newattlist, updateattlist, userbiss);
									}else{
										msg="{\"code\":\"2\",\"msg\":\"获取排班信息失败\"}";
									}
									if(newattlist!=null&&newattlist.size()>0){
										for (TAttendance newatt : newattlist) {
											attendanceService.insertTAttendance(newatt);
										}
									}
									if(updateattlist!=null&&updateattlist.size()>0){
										for (TAttendance updateatt : updateattlist) {
											attendanceService.updateTAttendance(updateatt);
										}
									}
								}
							}
							if(maindata.getType()==5){//补卡申请修改
								TFillcard fill=fillcardService.getTFillcardById(maindata.getBusinessid());
								if(fill!=null){
									TAttendance att=attendanceService.selectTAttendanceId(String.valueOf(fill.getAttendanceid()));
									if(att!=null){
										if(fill.getType()==1){
											att.setStarttime1(fill.getFilltime());
											att.setResults1(0);
										}else if(fill.getType()==2){
											att.setEndtime1(fill.getFilltime());
											att.setResults2(0);
										}else if(fill.getType()==3){
											att.setStarttime2(fill.getFilltime());
											att.setResults3(0);
										}else if(fill.getType()==4){
											att.setEndtime2(fill.getFilltime());
											att.setResults4(0);
										}else if(fill.getType()==5){
											att.setStarttime3(fill.getFilltime());
											att.setResults5(0);
										}else if(fill.getType()==6){
											att.setEndtime3(fill.getFilltime());
											att.setResults6(0);
										}
										attendanceService.updateTAttendance(att);
									}else{
										Long date=fill.getFilltime();//重置服务器当前时间
										TSchedulingdetails details=schedulingdetailsService.getTSchedulingdetailsById(fill.getDetailsid());
										if(date-fill.getFilltime()<=60000&&date-fill.getFilltime()>=-60000){
											date=fill.getFilltime();
										}
										TClocktime cktim=new TClocktime();
										String type=String.valueOf(fill.getType());
										userbiss=userService.selectTUserId(String.valueOf(fill.getUserid()));
										attendanceController.insertTAttendance(userbiss, details, cktim, type, date,"0", "0", 0, 0, 
												null, 0, maindata.getOrganizationId(),2);
									}
								}
							}
						}else{
							msg="{\"code\":\"2\",\"msg\":\"审批办理失败\"}";
						}
					}else{
						msg="{\"code\":\"2\",\"msg\":\"审批办理失败\"}";
					}
				}
			}else if(record.getRecordtype()==2){
				//抄送
				record.setDocstatus(3);
				record.setHandlestatus(1);
				record.setEndtime(handletime);
				record.setMidifytime(handletime);
				if(remarktype!=null && remarktype!="" && !"".equals(remarktype)){
					record.setRemarktype(Integer.parseInt(remarktype));
				}
				if(remark!=null && remark!="" && !"".equals(remark)){
					record.setRemark(remark);
				}
				int falre=recordService.updateTRecord(record);
				if(falre>0){
					//判断是否还存在抄送记录  如无：归档
					int num=recordService.getRecordCopyNum(docunid);
					if(num>0){
						msg="{\"code\":\"1\",\"msg\":\"抄送已读标记成功\"}";
					}else{
						msg="{\"code\":\"1\",\"msg\":\"抄送已读标记成功,实例数据已归档\"}";
					}
				}else{
					msg="{\"code\":\"2\",\"msg\":\"抄送已读标记失败\"}";
				}
			}
		}else{
			msg="{\"code\":\"2\",\"msg\":\"实例不存在或实例流转记录不存在\"}";
		}
		return msg;
	}
	
	/**
	 *获取当前用户相关的审批实例
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/getMyApproveList", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String getMyApproveList(HttpServletRequest request,Model model){
		int pageSize = 10;
		String userid = null;
		JSONObject jsonObject = null;
		String msg = null;
		String currentPageStr=null;
		String searchStr=null;
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		jsonObject = JSONObject.fromObject(json);
		try{
			userid =jsonObject.getString("userid");
			currentPageStr =jsonObject.getString("currentPageStr");
			searchStr =jsonObject.getString("searchStr");
		}catch(Exception e){
            msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
		int currentPage = 1;
		try {
			if(currentPageStr!=null && currentPageStr!=""){
				currentPage = Integer.parseInt(currentPageStr);
			}
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage; 
		int totalNum = maindataService.getMyApproveListNum(userid,searchStr);
		int totalPage = totalNum / pageSize;
		if (totalNum % pageSize != 0) {
			totalPage++;	
		}
		totalPage = totalPage <= 0 ? 1 : totalPage;
		currentPage = currentPage > totalPage ? totalPage : currentPage;
		List<TMaindata> list=maindataService.getMyApproveList(userid, (currentPage - 1) * pageSize, pageSize,searchStr);
		msg = "{\"code\":" +1+"," 
				+"\"data\":{"
				+"\"total\":" +totalNum +"," 
	    		+ "\"currentPage\":"+ currentPage+","
	    		+ "\"pageSize\":"+ pageSize+","
	    		+"\"approvelist\":[";
		int n = 0;
		 for(TMaindata maindata:list){
		    	if (n > 0) {
					msg += ",";
				}
		    	n++;
		    	//增加业务时，需要修改
		    	String description="";
		    	if(maindata.getLeave().getReason()!=null&&maindata.getLeave().getReason()!=""){
		    		description=maindata.getLeave().getReason();
		    	}else if(maindata.getOvertime().getOvertimereason()!=null&&maindata.getOvertime().getOvertimereason()!=""){
		    		description=maindata.getOvertime().getOvertimereason();
		    	}else if(maindata.getFill().getRemark()!=null&&maindata.getFill().getRemark()!=""){
		    		description=maindata.getFill().getRemark();
		    	}else if(maindata.getBorrow().getReason()!=null&&maindata.getBorrow().getReason()!=""){
		    		description=maindata.getBorrow().getReason();
		    	}else if(maindata.getEncy().getDetails()!=null&&maindata.getEncy().getDetails()!=""){
		    		description=maindata.getEncy().getDetails();
		    	}
		    	msg += "{\"docid\":" + maindata.getId() + ","
						+ "\"bussineeid\":\""+ maindata.getBusinessid()+ "\","
						+ "\"title\":\"" + maindata.getTitle()+ "\"," 
						+ "\"status\":\""+ maindata.getStatus() + "\","
						+ "\"passstatus\":\""+ maindata.getPassstatus() + "\","
						+ "\"modifytime\":\""+ maindata.getMidifytime() + "\","
						+ "\"applytime\":\""+ maindata.getCreatetime() + "\","
						+ "\"description\":\""+ description + "\","
						+ "\"type\":\""+ maindata.getType() + "\""
						+ "}";
		    }
		    msg += "]}}";
		return msg;
	}
	
	/**
	 * 封装请假考勤信息
	 * @param clolist
	 * @param newattlist
	 * @param updateattlist
	 * @param userbiss
	 */
	public void setLesveAttendance(List<TClocktime> clolist,List<TAttendance> newattlist,List<TAttendance> updateattlist,
			TUser userbiss){
		long starttime=0;
		long endtime=0;
		for (TClocktime clo : clolist) {
			starttime=DateUtil.getStartTime(0, clo.getTime()).getTime();
			endtime=DateUtil.getnowEndTime(23, clo.getTime()).getTime();
			List<TAttendance> attlist=attendanceService.selectTAttendanceListName(userbiss.getId(), starttime, endtime);
			if(attlist!=null&&attlist.size()>0){
				if(clo.getSort()==1){
					for (TAttendance att : attlist) {
						att.setStarttime1(clo.getTime());
						att.setResults1(0);
						updateattlist.add(att);
					}
				}else if(clo.getSort()==2){
					for (TAttendance att : attlist) {
						att.setEndtime1(clo.getTime());
						att.setResults2(0);
						updateattlist.add(att);
					}
				}else if(clo.getSort()==3){
					for (TAttendance att : attlist) {
						att.setStarttime2(clo.getTime());
						att.setResults3(0);
						updateattlist.add(att);
					}
				}else if(clo.getSort()==4){
					for (TAttendance att : attlist) {
						att.setEndtime2(clo.getTime());
						att.setResults4(0);
						updateattlist.add(att);
					}
				}else if(clo.getSort()==5){
					for (TAttendance att : attlist) {
						att.setStarttime3(clo.getTime());
						att.setResults5(0);
						updateattlist.add(att);
					}
				}else if(clo.getSort()==6){
					for (TAttendance att : attlist) {
						att.setEndtime3(clo.getTime());
						att.setResults6(0);
						updateattlist.add(att);
					}
				}
			}else{
				if(newattlist!=null&&newattlist.size()>0){
					for (TAttendance newatt : newattlist) {
						if(newatt.getCreatetime()<=clo.getTime()&&newatt.getCreatetime()>=clo.getTime()){
							if(clo.getSort()==1){
								newatt.setStarttime1(clo.getTime());
								newatt.setResults1(0);
							}else if(clo.getSort()==2){
								newatt.setEndtime1(clo.getTime());
								newatt.setResults2(0);
							}else if(clo.getSort()==3){
								newatt.setStarttime2(clo.getTime());
								newatt.setResults3(0);
							}else if(clo.getSort()==4){
								newatt.setEndtime2(clo.getTime());
								newatt.setResults4(0);
							}else if(clo.getSort()==5){
								newatt.setStarttime3(clo.getTime());
								newatt.setResults5(0);
							}else if(clo.getSort()==6){
								newatt.setEndtime3(clo.getTime());
								newatt.setResults6(0);
							}
						}
					}
				}else{
					TAttendance att=new TAttendance();
					if(clo.getSort()==1){
						att.setStarttime1(clo.getTime());
						att.setResults1(0);
					}else if(clo.getSort()==2){
						att.setEndtime1(clo.getTime());
						att.setResults2(0);
					}else if(clo.getSort()==3){
						att.setStarttime2(clo.getTime());
						att.setResults3(0);
					}else if(clo.getSort()==4){
						att.setEndtime2(clo.getTime());
						att.setResults4(0);
					}else if(clo.getSort()==5){
						att.setStarttime3(clo.getTime());
						att.setResults5(0);
					}else if(clo.getSort()==6){
						att.setEndtime3(clo.getTime());
						att.setResults6(0);
					}
					att.setUserId(userbiss.getId());
					att.setSchedulingId(userbiss.getSchedulingId());
					att.setOrganizationId(userbiss.getOrganizationId());
					att.setCreatetime(clo.getTime());
					newattlist.add(att);
				}
			}
		}
	}
	/**
	 * 公司列表
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/companyList",method=RequestMethod.POST,produces="text/json;charset=UTF-8")
	@ResponseBody
	public String companyList(HttpServletRequest request,Model model){
		String organizationid = null;
		String userid = null;
		JSONObject jsonObject = null;
		String msg = null;
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		jsonObject = JSONObject.fromObject(json);
		try{
			organizationid=jsonObject.getString("organizationid");
			userid=jsonObject.getString("userid");
		}catch(Exception e){
            msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
		if (userid != null) {
			List<TOrganization> organizations = userService.getOrganization(userid);
			HashMap<String, Object> map = new HashMap<String, Object>();
			HashMap<String, Object> map1 = new HashMap<String, Object>();
			map.put("organizations", organizations);
			map1.put("data", map);
			map1.put("code", 1);
			JSONObject jsons = JSONObject.fromObject(map1);// 将java对象转换为json对象
			msg = jsons.toString();
		}
		return msg;
	}

	@RequestMapping(value="/switchoverCompany",method=RequestMethod.POST,produces="text/json;charset=UTF-8")
	@ResponseBody
	public String switchoverCompany(HttpServletRequest request,Model model){
		String organizationid = null;
		JSONObject jsonObject = null;
		String msg = null;
		String customaryOrganizationid = null;
		String userid = null;
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		jsonObject = JSONObject.fromObject(json);
		try{
			customaryOrganizationid=jsonObject.getString("customaryOrganizationid");
			userid=jsonObject.getString("userid");
			organizationid=jsonObject.getString("organizationid");
		}catch(Exception e){
            msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
		if (organizationid != null) {
			TUser user = userBeanService.getUserList(customaryOrganizationid,userid);
			HashMap<String, Object> map = new HashMap<String, Object>();
			HashMap<String, Object> map2 = new HashMap<String, Object>();
			map2.put("dept", user.getDept());
			map2.put("englishname", user.getEnglishname());
			map2.put("id", user.getId());
			map2.put("jobnumber", user.getJobnumber());
			map2.put("loginname", user.getLoginname());
			map2.put("logintime", user.getLogintime());
			map2.put("name", user.getName());
			map2.put("organizationId", user.getOrganizationId());      
			map2.put("password", user.getPassword());
			map2.put("paylist", user.getPaylist());
			map2.put("role", user.getRole());
			map2.put("status", user.getStatus());
			map2.put("token", user.getToken());
			map2.put("whetheronline", user.getWhetheronline());
			map.put("data", map2);
			map.put("code", 1);
			JSONObject jsons = JSONObject.fromObject(map);// 将java对象转换为json对象
			msg = jsons.toString();
		}
		return msg;
	}
}
